const nickDiv = document.querySelector('.nick')
const nickP = document.querySelector('.nickP')
const logout = document.querySelector('.logout')
const go_cart = document.querySelector('.go_cart')
const go_index = document.querySelector('.go_index')
const searchInp = document.querySelector('.search_inp input')
const ul = document.querySelector('.search_inp ul')
const back = document.querySelector('.back')
const content_list = document.querySelector('.content_list')
const two_box = document.querySelector('.two_box')
const product_box = document.querySelector('.product_box')
const prev = document.querySelector('.prev')
const next = document.querySelector('.next')
const pageInfo = document.querySelector('.pageInfo')
const sort = document.querySelector('.sort')
const go_login = document.querySelector('.go_login')

const login = window.localStorage.getItem('login')
const nick = window.localStorage.getItem('nick')

// 给帮助中心添加鼠标移入事件,移入时给盒子添加类名让其显示
$('.help').mouseover(function () {
    $('.help_box').stop().slideDown(300, 'linear')//.addClass('active')
})
$('.help').mouseout(function () {
    $('.help_box').stop().slideUp(300, 'linear')//.addClass('active')
})

nickHtml()
function nickHtml() {
    if (!login) {
        loginDiv.classList.add('active')
        return
    }
    nickDiv.classList.add('active')

    // 登录过将用户名写入
    nickP.innerText = 'hello ' + nick
}

// 在线咨询
$('.consult').mouseover(function () {
    $(this).addClass('active')
    console.log($(this))
})
$('.consult').mouseout(function () {
    $(this).removeClass('active')
})

// 登录注册下滑盒子
$('.login').mouseover(function () {
    $('.login_box').stop().slideDown(500, 'linear')
})
$('.login').mouseleave(function () {
    $('.login_box').stop().slideUp(500, 'linear')
})
// 注销登录盒子的显示
$('.nick').mouseover(function () {
    $('.nick_box').stop().slideDown(500, 'linear')
})
$('.nick').mouseleave(function () {
    $('.nick_box').stop().slideUp(500, 'linear')
})

// 登录事件
go_login.addEventListener('click', () => {
    window.location.href = './login.html'
})

// 注销绑定事件
logout.onclick = () => {
    window.localStorage.removeItem('id')
    window.localStorage.removeItem('login')
    window.localStorage.removeItem('nick')
    nickDiv.classList.remove('active')
    loginDiv.classList.add('active')
}

// 跳转购物车
go_cart.onclick = function () {
    // 获取login 没有的话代表没有登陆过 需要先登录
    const login = window.localStorage.getItem('login')
    if (!login) {
        alert('您还没有登录哦,请先登录吧^_^')
        window.location.href = './login.html'
        return
    }
    window.location.href = './cart.html'
}

// 返回首页
go_index.onclick = () => {
    window.location.href = './index.html'
}

// 二级菜单
// 获取li的index,上边ul的li索引-1对应的是下边要显示的li
$('.nav_box>li').mouseover(function () {
    const index = $(this).index()
    let i = index - 1
    if (i >= 0) {
        $('.header_box>li').eq(i).finish().slideDown(300, 'linear').siblings().finish().slideUp(0)
    }
})
$('.header_box').mouseleave(function () {
    $('.header_box>li').finish().slideUp(0)
})


$('.search').mouseover(function () {
    $('.search_inpbox').stop().slideDown(500, 'linear')
})
$('.search').mouseout(function () {
    $('.search_inpbox').stop().slideUp(500, 'linear')
})

// 搜索引擎
searchInp.oninput = function () {

    const text = this.value.trim()
    console.log(text)
    const script = document.createElement('script')
    script.src = `https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=34305,34099,33970,34273,34278,34004,34281,34107,34111,26350,22159&wd=${text}&req=2&csor=2&cb=fn&_=1627023610785`
    document.body.appendChild(script)

    script.remove()
}

function fn(res) {

    if (!res.g) {
        // 说明没有 g 这个数组
        ul.classList.remove('active')
        return
    }

    let str = ''
    res.g.forEach(item => {
        str += `<li>${item.q}</li>`
    })

    ul.innerHTML = str

    ul.classList.add('active')
}
// 给返回顶部的图片添加事件

window.addEventListener('scroll', function () {
    const scrollTop = document.documentElement.scrollTop
    if (scrollTop >= 300) {
        back.classList.add('active')
    } else {
        back.classList.remove('active')
    }
})
back.addEventListener('click', () => {
    window.scrollTo({
        top: 0,
        behavior: "smooth"
    })
})

// 发送请求渲染
const xhr = new XMLHttpRequest
xhr.open('POST', '/hln')
xhr.onload = () => {
    const res = JSON.parse(xhr.responseText)
    const res1 = res.serializableData.aggResult.productList
    console.log(res1)
    titleHtml(res1)
    bindHtml(res1)
}
xhr.setRequestHeader('content-type', 'application/json')
xhr.send('{"addedCategoryCode": "bros_skincare","channelCode": "BROS","filterCategoryCode": [["bros_skincare"]],"filterMainCategoryCode": "bros_skincare","page": 0,"searchCategoryCode": "bros_skincare","sortField": "","sortOrder": ""}');

let current = 1
let pagesize = 12
let total = 0
function titleHtml(xhr) {
    // const res = JSON.parse(xhr.responseText)
    let str = ''
    let arr = []
    xhr.forEach((item) => {
        if (arr.indexOf(item.labelNameList[1]) === -1 && item.labelNameList[1]) {
            arr.push(item.labelNameList[1])
        }
    })
    arr.forEach(item => {
        str += `
            <li class="two" data-t="${item}">${item}
            </li>
        `
    })
    two_box.innerHTML = str
}
function bindHtml(xhr) {
    let total = Math.ceil(xhr.length / pagesize)
    pageInfo.innerText = `${current}/${total}`

    let bind = xhr.slice((current - 1) * pagesize, current * pagesize)
    let str1 = ''
    bind.forEach(item => {
        str1 += `
        <li class="p_box1" data-group="${item.labelNameList[1]}">
          <div class="p_img">
            <img class="img1" data-id="${item.id}" src="${item.productImages[0]}" alt="">
          </div>
          <p class="p_t1">${item.productName}</p>
          <p class="p_t2">${item.productNameEn}</p>
          <p class="p_t3"><span>￥</span>${item.defaultPrice}</p>
          <select>
            <option value="${item.variantValueList[0]}">${item.variantValueList[0]}</option>
            <option value="${item.variantValueList[1]}">${item.variantValueList[1]}</option>
            <option value="${item.variantValueList[2]}">${item.variantValueList[2]}</option>
          </select>
          <button data-id="${item.id}" class="buy_btn">立即购买</button>
        </li>
        `
    })
    product_box.innerHTML = str1

    prev.className = current <= 1 ? 'prev disable' : 'prev'

    next.className = current >= total ? 'next disable' : 'next'

    // 上一页
    prev.onclick = function () {
        if (current <= 1) return
        current--
        bindHtml(xhr)
    }
    next.onclick = function () {
        if (current >= total) return
        current++
        bindHtml(xhr)
    }

    // 添加点击事件跳转详情页
    product_box.addEventListener('click', e => {
        e = e || window.event
        const target = e.target || e.srcElement
        // 跳转详情页
        if (target.className === 'img1') {
            const productId = target.dataset.id
            window.localStorage.setItem('product_id', productId)
            window.location.href = './detail.html'
        }

        // 加入购物车
        if (target.className === 'buy_btn') {
            const login = window.localStorage.getItem('login')
            if (!login) {
                alert('您还没有登录哦,请先登录吧^_^')
                window.localStorage.setItem('url','list')
                window.location.href = './login.html'
                return
            }

            let goodsId = target.dataset.id
            var cartList = xhr.find(function (item) { return item.id === goodsId })
            var list1 = JSON.parse(window.localStorage.getItem('cart')) || []

            if (!list1.length) {
                cartList.cart_number = 1
                cartList.check = false
                list1.push(cartList)

            } else {
                var res = list1.some(function (item) { return item.id === goodsId })
                if (res) {
                    var index = list1.findIndex(function (item) { return item.id === goodsId })
                    list1[index].cart_number++
                    list1[index].check = false
                } else {
                    cartList.cart_number = 1
                    cartList.check = false
                    list1.push(cartList)
                }
            }
            window.localStorage.setItem('cart', JSON.stringify(list1))
            alert('加入购物车成功')
        }

    })
}
sort.addEventListener('change', () => {
    const val = sort.value
    if (val === 'all') {
        bindHtml(xhr)
    }
    if (val === 'asc') {
        const xhr = new XMLHttpRequest
        xhr.open('POST', '/hln')
        xhr.onload = () => {
            const res = JSON.parse(xhr.responseText)
            const res1 = res.serializableData.aggResult.productList
            bindHtml(res1)
        }
        xhr.setRequestHeader('content-type', 'application/json')
        xhr.send('{"addedCategoryCode":"bros_skincare","searchCategoryCode":"bros_skincare","channelCode":"BROS","filterMainCategoryCode":"bros_skincare","page":0,"sortField":"defaultPrice","sortOrder":"asc","filterCategoryCode":[["bros_skincare"]],"enablePriceRange":true}')
        current = 1
    }
    if (val === 'desc') {
        const xhr = new XMLHttpRequest
        xhr.open('POST', '/hln')
        xhr.onload = () => {
            const res = JSON.parse(xhr.responseText)
            const res1 = res.serializableData.aggResult.productList
            bindHtml(res1)
        }
        xhr.setRequestHeader('content-type', 'application/json')
        xhr.send('{"addedCategoryCode":"bros_skincare","searchCategoryCode":"bros_skincare","channelCode":"BROS","filterMainCategoryCode":"bros_skincare","page":0,"sortField":"defaultPrice","sortOrder":"desc","filterCategoryCode":[["bros_skincare"]],"enablePriceRange":true}')
        current = 1
    }
})

// 分类筛选

$('.one').click(function () {
    $(this).toggleClass('active')

    $(this).parent().parent().find('.two_box').finish().slideToggle()
})

two_box.addEventListener('click', e => {
    e = e || window.event
    const target = e.target || e.srcElement
    if (target.className === 'two') {
        const t = target.dataset.t
        const xhr = new XMLHttpRequest
        xhr.open('POST', '/hln')
        xhr.onload = () => {
            const res = JSON.parse(xhr.responseText)
            let list2 = res.serializableData.aggResult.productList
            let list3 = []
            list2.forEach(function (item) {
                if (item.labelNameList[1] === t) {
                    list3.push(item)
                }
            })
            console.log(list3)
            bindHtml(list3)
        }
        xhr.setRequestHeader('content-type', 'application/json')
        xhr.send('{"addedCategoryCode": "bros_skincare","channelCode": "BROS","filterCategoryCode": [["bros_skincare"]],"filterMainCategoryCode": "bros_skincare","page": 0,"searchCategoryCode": "bros_skincare","sortField": "","sortOrder": ""}');

    }
})